Stock Market Analysis using Python¶

Stock Market Performance Analysis involves calculating moving averages, measuring volatility, conducting correlation analysis and analyzing various aspects of the stock market to gain a deeper understanding of the factors that affect stock prices and the relationships between the stock prices of different companies¶

Installing yfinance library for downloading the stock prices¶

In [3]:
!pip install yfinance
Requirement already satisfied: yfinance in c:\users\asifd\anaconda3\lib\site-packages (0.2.41)
Requirement already satisfied: pandas>=1.3.0 in c:\users\asifd\anaconda3\lib\site-packages (from yfinance) (2.1.1)
Requirement already satisfied: numpy>=1.16.5 in c:\users\asifd\anaconda3\lib\site-packages (from yfinance) (1.24.3)
Requirement already satisfied: requests>=2.31 in c:\users\asifd\anaconda3\lib\site-packages (from yfinance) (2.31.0)
Requirement already satisfied: multitasking>=0.0.7 in c:\users\asifd\anaconda3\lib\site-packages (from yfinance) (0.0.11)
Requirement already satisfied: lxml>=4.9.1 in c:\users\asifd\anaconda3\lib\site-packages (from yfinance) (4.9.2)
Requirement already satisfied: platformdirs>=2.0.0 in c:\users\asifd\anaconda3\lib\site-packages (from yfinance) (2.5.2)
Requirement already satisfied: pytz>=2022.5 in c:\users\asifd\anaconda3\lib\site-packages (from yfinance) (2022.7)
Requirement already satisfied: frozendict>=2.3.4 in c:\users\asifd\anaconda3\lib\site-packages (from yfinance) (2.4.4)
Requirement already satisfied: peewee>=3.16.2 in c:\users\asifd\anaconda3\lib\site-packages (from yfinance) (3.17.6)
Requirement already satisfied: beautifulsoup4>=4.11.1 in c:\users\asifd\anaconda3\lib\site-packages (from yfinance) (4.12.2)
Requirement already satisfied: html5lib>=1.1 in c:\users\asifd\anaconda3\lib\site-packages (from yfinance) (1.1)
Requirement already satisfied: soupsieve>1.2 in c:\users\asifd\anaconda3\lib\site-packages (from beautifulsoup4>=4.11.1->yfinance) (2.4)
Requirement already satisfied: six>=1.9 in c:\users\asifd\anaconda3\lib\site-packages (from html5lib>=1.1->yfinance) (1.16.0)
Requirement already satisfied: webencodings in c:\users\asifd\anaconda3\lib\site-packages (from html5lib>=1.1->yfinance) (0.5.1)
Requirement already satisfied: python-dateutil>=2.8.2 in c:\users\asifd\appdata\roaming\python\python311\site-packages (from pandas>=1.3.0->yfinance) (2.8.2)
Requirement already satisfied: tzdata>=2022.1 in c:\users\asifd\anaconda3\lib\site-packages (from pandas>=1.3.0->yfinance) (2023.3)
Requirement already satisfied: charset-normalizer<4,>=2 in c:\users\asifd\anaconda3\lib\site-packages (from requests>=2.31->yfinance) (2.0.4)
Requirement already satisfied: idna<4,>=2.5 in c:\users\asifd\anaconda3\lib\site-packages (from requests>=2.31->yfinance) (3.4)
Requirement already satisfied: urllib3<3,>=1.21.1 in c:\users\asifd\anaconda3\lib\site-packages (from requests>=2.31->yfinance) (1.26.16)
Requirement already satisfied: certifi>=2017.4.17 in c:\users\asifd\anaconda3\lib\site-packages (from requests>=2.31->yfinance) (2024.6.2)

Importing otherlibraires like pandas to view and clean the data. Importing yfinance and datetime modules and plotly express for data viualization¶

In [5]:
import pandas as pd
import yfinance as yf
from datetime import datetime
import plotly.express as px
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings('ignore')

Going to analyse data from 3 months before to date¶

In [7]:
start_date = datetime.now() - pd.DateOffset(months=3)
end_date = datetime.now()

Analyse stock for the these companies Reliance, TCS, HDFC Bank and ICICI Bank¶

In [13]:
tickers=['RELIANCE.NS' , 'TCS.NS' , 'HDFCBANK.NS', 'ICICIBANK.NS']
str_tickers =", ".join(tickers)
str_tickers
Out[13]:
'RELIANCE.NS, TCS.NS, HDFCBANK.NS, ICICIBANK.NS'

Getting the data and saving it to dataframe¶

In [15]:
df_list =[]

for ticker in tickers:
    data = yf.download(ticker,start=start_date, end=end_date)
    df_list.append(data)

df=pd.concat(df_list,keys=tickers,names=['Ticker', 'Date'])
df.head()
[*********************100%%**********************]  1 of 1 completed
[*********************100%%**********************]  1 of 1 completed
[*********************100%%**********************]  1 of 1 completed
[*********************100%%**********************]  1 of 1 completed
Out[15]:
Open High Low Close Adj Close Volume
Ticker Date
RELIANCE.NS 2024-04-22 2944.899902 2965.649902 2935.600098 2959.699951 2959.699951 5175181
2024-04-23 2958.000000 2987.000000 2911.100098 2918.649902 2918.649902 7302777
2024-04-24 2927.000000 2937.100098 2899.000000 2900.350098 2900.350098 5231388
2024-04-25 2885.000000 2935.949951 2883.000000 2919.949951 2919.949951 7971963
2024-04-26 2927.899902 2930.000000 2900.000000 2905.100098 2905.100098 4706924
In [17]:
df=df.reset_index()
df.tail()
Out[17]:
Ticker Date Open High Low Close Adj Close Volume
239 ICICIBANK.NS 2024-07-12 1235.900024 1252.900024 1230.099976 1232.900024 1232.900024 12208290
240 ICICIBANK.NS 2024-07-15 1233.099976 1238.449951 1224.050049 1229.949951 1229.949951 15612671
241 ICICIBANK.NS 2024-07-16 1230.000000 1245.000000 1229.000000 1239.900024 1239.900024 12320605
242 ICICIBANK.NS 2024-07-18 1234.900024 1256.449951 1231.699951 1250.300049 1250.300049 10999632
243 ICICIBANK.NS 2024-07-19 1244.000000 1250.500000 1240.250000 1248.650024 1248.650024 7958817
In [19]:
df.dtypes
Out[19]:
Ticker               object
Date         datetime64[ns]
Open                float64
High                float64
Low                 float64
Close               float64
Adj Close           float64
Volume                int64
dtype: object

View perfomance of these tickers¶

Market Cap¶

In [21]:
df['Market_Cap']= df['Open'] * df['Volume']
In [23]:
df.head()
Out[23]:
Ticker Date Open High Low Close Adj Close Volume Market_Cap
0 RELIANCE.NS 2024-04-22 2944.899902 2965.649902 2935.600098 2959.699951 2959.699951 5175181 1.524039e+10
1 RELIANCE.NS 2024-04-23 2958.000000 2987.000000 2911.100098 2918.649902 2918.649902 7302777 2.160161e+10
2 RELIANCE.NS 2024-04-24 2927.000000 2937.100098 2899.000000 2900.350098 2900.350098 5231388 1.531227e+10
3 RELIANCE.NS 2024-04-25 2885.000000 2935.949951 2883.000000 2919.949951 2919.949951 7971963 2.299911e+10
4 RELIANCE.NS 2024-04-26 2927.899902 2930.000000 2900.000000 2905.100098 2905.100098 4706924 1.378140e+10
In [25]:
fig=px.line(df, x='Date', y='Close', color='Ticker', title='Stock market perfomance for last 3 Months', width=800, height=600)

fig.show()

Area chart to compare the perfomance¶

In [27]:
fig =px.area( df, x='Date', y='Close', color='Ticker',
             facet_col ='Ticker',
             labels={'Date':'Date', 'Close':'Closing Price', 'Ticker':'Company'},
             title=f' Stock Prices for {str_tickers}', height=600)
fig.show()

Area Chart to compare the Volume¶

In [29]:
fig =px.area( df, x='Date', y='Volume', color='Ticker',
             facet_col ='Ticker',
             labels={'Date':'Date', 'Volume':'Volume', 'Ticker':'Company'},
             title=f'Volume for {str_tickers}', height=600)
fig.show()

Market Cap for the Seelcted Stocks¶

In [33]:
fig =px.area( df, x='Date', y='Market_Cap', color='Ticker',
             facet_col ='Ticker',
             labels={'Date':'Date', 'Market_Cap':'Market Cap', 'Ticker':'Company'},
             title=f'Market Cap for {str_tickers}', height=600)
fig.show()

Analyse moving averages, which provide a useful way to identify trends and patterns in each company’s stock price movements over a period of time¶

In [35]:
df['MA10'] = df.groupby('Ticker')['Close'].rolling(window=10).mean().reset_index(0,drop=True)
df['MA20'] =df.groupby('Ticker')['Close'].rolling(window=20).mean().reset_index(0,drop=True)
In [37]:
for ticker,group in df.groupby('Ticker'):
    fig=px.line(group, x='Date', y=['Close', 'MA10', 'MA20'],
                title=f"{ticker} Moving Average")
    fig.show()

Visualization of the percent change for each day¶

In [39]:
df['Daily_Return'] = df['Adj Close'].pct_change()
df.head()
Out[39]:
Ticker Date Open High Low Close Adj Close Volume Market_Cap MA10 MA20 Daily_Return
0 RELIANCE.NS 2024-04-22 2944.899902 2965.649902 2935.600098 2959.699951 2959.699951 5175181 1.524039e+10 NaN NaN NaN
1 RELIANCE.NS 2024-04-23 2958.000000 2987.000000 2911.100098 2918.649902 2918.649902 7302777 2.160161e+10 NaN NaN -0.013870
2 RELIANCE.NS 2024-04-24 2927.000000 2937.100098 2899.000000 2900.350098 2900.350098 5231388 1.531227e+10 NaN NaN -0.006270
3 RELIANCE.NS 2024-04-25 2885.000000 2935.949951 2883.000000 2919.949951 2919.949951 7971963 2.299911e+10 NaN NaN 0.006758
4 RELIANCE.NS 2024-04-26 2927.899902 2930.000000 2900.000000 2905.100098 2905.100098 4706924 1.378140e+10 NaN NaN -0.005086
In [41]:
for ticker,group in df.groupby('Ticker'):
    fig=px.line(group, x='Date', y='Daily_Return',
                title=f"{ticker} Daily_Return", markers=True)
    fig.update_traces(patch={"line": {"dash": "dashdot",
                           "shape": "spline",
                           "width": 1}})
    fig.show()

Visualizing as a Histogram¶

In [43]:
for ticker,group in df.groupby('Ticker'):
    fig=px.histogram(group,  x='Daily_Return',
                title=f"{ticker} Daily_Return",nbins=50 )
    fig.show()

Visualize the volatility of all companies. Volatility is a measure of how much and how often the stock price or market fluctuates over a given period of time¶

In [45]:
df['Volatility'] = df.groupby('Ticker')['Close'].pct_change().rolling(window=10).std().reset_index(0, drop=True)
fig = px.line(df, x='Date', y='Volatility', 
              color='Ticker', 
              title='Volatility of All Companies')
fig.show()

This completes the Stock market Analysis of Sock market performance using Python, Pandas, yfinance¶

Asif Dawood¶

In [ ]: